package game.Engine.Entity;

import game.MainController;
import game.display.Animation;
import game.display.Images;

public class AlienSpawn extends Entity
{
	private transient Alien[] aliens;
	private transient long timer;
	private transient Animation anim;
	public final static long BASE_TIMER = 30000000000l;

	public AlienSpawn(double x, double y, Animation gi) {
		super(x, y, gi);
		aliens = new Alien[4];
		timer = 0;
	}

	public void updateImage(){
		if(anim == null)
			gi = anim = Images.SPAWNPOINT.image();
		else
			gi = anim;
	}
	
	public void update(long timeElapsed) {
		super.update(timeElapsed);
		boolean emptySpot = false;
		boolean oneSleeping = false;
		int emptyIndex = -1;
		for (int i = 0; i < aliens.length; i++) {
			if (aliens[i] == null) {
				emptySpot = true;
				emptyIndex = i;
			} else {
				if (aliens[i].getState() == State.SLEEPING) {
					oneSleeping = true;
				} else if (aliens[i].getState() == State.DEAD) {
					aliens[i] = null;
					emptySpot = true;
					emptyIndex = i;
				}
			}
		}
		if (!oneSleeping) {
			if (emptySpot) {
				if (timer <= 0) {
					timer += BASE_TIMER;
					aliens[emptyIndex] = new Alien(getX(), getY());
					MainController.gameEngine.addEntity(aliens[emptyIndex]);
				} else {
					timer -= timeElapsed;
				}
			}
		}
	}
	
	public void matchWith(AlienSpawn a){
		z = a.getZ();
		x = a.getX();
		y = a.getY();
		dx = a.getVelocityX();
		dy = a.getVelocityY();
		state = a.getState();
	}

}
